import scala.collection.immutable
import scala.io.{BufferedSource, Source}

object Demo13WordCountScala {
  def main(args: Array[String]): Unit = {
    // 使用函数式编程的思想完成WordCount
    /**
     * 提示：使用flatMap方法可以将每行数据切分后的结果进行展开
     */

    // 1、读文件
    val bs: BufferedSource = Source
      .fromFile("Scala/data/words.txt")

    val lines: List[String] = bs.getLines().toList

    // 2、按照","切分 将每一行所有的单词 变成一列
    val words: List[String] = lines.flatMap(line => line.split(","))

    // 3、进行分组
    val groupWords: Map[String, List[String]] = words.groupBy(word => word)

    // 4、统计每个单词的数量
    val wordCnt: immutable.Iterable[String] = groupWords.map(kv => kv._1 + "," + kv._2.size)

    // 5、打印
    wordCnt.foreach(println)

    // 链式调用
    Source
      .fromFile("Scala/data/words.txt")
      .getLines()
      .toList
      .flatMap(_.split(","))
      .groupBy(word => word)
      .map(kv => kv._1 + "," + kv._2.size)
      .foreach(println)

  }

}
